package jastgen.generator;

import static jastgen.generator.Helper.*;
import java.io.PrintWriter;
import jastgen.CompileException;
import jastgen.nodes.ClassDef;
import jastgen.nodes.Module;

class NodesCollectorBodyGenerator implements BodyGenerator {

	private final Module node;

	NodesCollectorBodyGenerator(
			final Module node
		) throws CompileException {

		this.node = node;
	}

	public void generate(
			final PrintWriter out)
	{
		generateVisitorBody(out, node);
	}

	private void generateVisitorBody(
			final PrintWriter out,
			final Module node)
	{
		out.println("final class NodesCollector extends VoidVisitorAdapter {");
		out.println();
		out.println("	Context context = new Context();");

		for(final ClassDef c : node.getClassDefs()) {
			// フィールドが存在しなければsingletonなのでmapは不要
			if(!c.hasNormalFields())
				continue;
			out.println();
			generateExitNode(out, c);
		}

		out.println("}");
	}

	private void generateExitNode(
			final PrintWriter out,
			final ClassDef c)
	{
		printVisitC(out, c, "exit");
		out.println("	{");
		out.println("		context.intern(node);");
		out.println("	}");
	}
}
